﻿using FileTransSystem.Helper;
using MaterialDesignThemes.Wpf;
using Panuon.UI.Silver;
using System;
using System.Configuration;
using System.Data;
using System.Data.SQLite;
using System.Windows;
using FileTransSystem.Model;

namespace FileTransSystem
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : WindowX
    {
        private SQLiteConnection sqLiteConnection;
        private UserModel userModel;

        public MainWindow()
        {
            InitializeComponent();
            TextBoxAccount.Text = ReadConfig("userName");

            if (ReadConfig("isRemember") == "True")
            {
                CheckBoxRemember.IsChecked = true;
                TextBoxPassword.Password = ReadConfig("password");
            }

            if (ReadConfig("isAutoLogin") == "True")
            {
                CheckBoxAutoLogin.IsChecked = true;
            }
        }

        public async void MessageTips(string message, object sender, RoutedEventArgs e, string identifier)
        {
            var sampleMessageDialog = new MessageDialog
            {
                Message = {Text = message}
            };
            await DialogHost.Show(sampleMessageDialog, identifier);
        }

        private void ButtonRegister_OnClick(object sender, RoutedEventArgs e)
        {
            this.Visibility = Visibility.Hidden;
            RegisterWindow registerWindow = new RegisterWindow(this);
            registerWindow.Show();
        }

        private void ButtonLogin_OnClick(object sender, RoutedEventArgs e)
        {
            string userName = TextBoxAccount.Text;
            string password = TextBoxPassword.Password;
            sqLiteConnection = GetSqlConnection.Connect();

            DataSet userDataSet = DatabaseHelper.ExecuteDataSet(sqLiteConnection,
                "select * from userAccount where account=@account",
                new object[1] {userName});
            DataTable table = userDataSet.Tables[0];

            if (string.IsNullOrWhiteSpace(TextBoxAccount.Text))
            {
                MessageTips("请输入用户名！", sender, e, "RootDialog");
            }
            else if (string.IsNullOrWhiteSpace(TextBoxPassword.Password))
            {
                MessageTips("请输入密码！", sender, e, "RootDialog");
            }
            else if (table.Rows.Count == 0 || verifyPassword(
                table.Rows[0]["password"].ToString(),
                table.Rows[0]["salt"].ToString()))
            {
                MessageTips("用户名或密码不正确！", sender, e, "RootDialog");
            }
            else
            {
                UpdateSettingString("userName", userName);
                UpdateSettingString("isRemember", CheckBoxRemember.IsChecked.ToString());
                UpdateSettingString("isAutoLogin", CheckBoxAutoLogin.IsChecked.ToString());
                if (CheckBoxRemember.IsChecked == true)
                {
                    UpdateSettingString("password", password);
                }

                userModel = new UserModel(userName, (string) table.Rows[0]["profile"], (string) table.Rows[0]["sex"],
                    (bool) table.Rows[0]["isAdmin"]);

                MessageTips("欢迎您，" + table.Rows[0]["account"].ToString() + "。身份：" +
                            ((bool) table.Rows[0]["isAdmin"] ? "管理员" : "用户"), sender, e, "RootLoginDialog");
            }
        }

        private bool verifyPassword(string password, string salt)
        {
            byte[] passwordAndSaltBytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
            byte[] hashBytes = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordAndSaltBytes);
            string hashString = Convert.ToBase64String(hashBytes);
            return hashString.Equals(password);
        }

        private void DialogHost_OnDialogClosing(object sender, DialogClosingEventArgs eventargs)
        {
            if (userModel.IsAdmin)
                new AdminManage().Show();
            else
                new FileManager(userModel).Show();
            this.Close();
        }

        /// <summary>
        /// 读取客户设置
        /// </summary>
        /// <param name="settingName"></param>
        /// <returns></returns>
        private static string ReadConfig(string settingName)
        {
            try
            {
                string settingString = ConfigurationManager.AppSettings[settingName].ToString();
                return settingString;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 更新设置
        /// </summary>
        /// <param name="settingName"></param>
        /// <param nme="valueName"></param>
        public static void UpdateSettingString(string settingName, string valueName)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (ConfigurationManager.AppSettings[settingName] != null)
            {
                config.AppSettings.Settings.Remove(settingName);
            }

            config.AppSettings.Settings.Add(settingName, valueName);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }
}